import { useState, useRef } from 'react';
import {
  Box,
  Button,
  Popover,
  TextField,
  Typography,
  Paper,
  IconButton,
  CircularProgress,
  Fab
} from '@mui/material';
import { QuestionAnswer as QuestionAnswerIcon, Send as SendIcon, Close as CloseIcon } from '@mui/icons-material';

interface Message {
  content: string;
  isUser: boolean;
  timestamp: Date;
}

const Assistant = () => {
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleSendMessage = async () => {
    if (!input.trim()) return;

    // 添加用户消息
    const userMessage: Message = {
      content: input,
      isUser: true,
      timestamp: new Date()
    };

    setMessages([...messages, userMessage]);
    setIsLoading(true);
    setInput('');

    try {
      // 调用Coze API
      const response = await fetch('https://api.coze.cn/v1/workflow/run', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer pat_rAK4ni2SSaq6hqSyqV6yfM2bib9DOXsNHpSQ4nvI65kcFlIpPFZ95MWHlNSH56SP',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          parameters: {
            input: input
          },
          workflow_id: '7515441253565186102'
        })
      });

      
      if (!response.ok) {
        throw new Error('API请求失败');
      }

      const data = await response.json();
      console.log(data);
      // 添加AI回复
      const aiMessage: Message = {
        content: JSON.parse(data.data).output || '抱歉，我无法处理您的请求',
        isUser: false,
        timestamp: new Date()
      };

      setMessages(prevMessages => [...prevMessages, aiMessage]);
    } catch (error) {
      console.error('调用AI助手API失败:', error);
      
      // 添加错误消息
      const errorMessage: Message = {
        content: '抱歉，发生了一些错误，请稍后再试。',
        isUser: false,
        timestamp: new Date()
      };

      setMessages(prevMessages => [...prevMessages, errorMessage]);
    } finally {
      setIsLoading(false);
      // 滚动到底部
      setTimeout(scrollToBottom, 100);
    }
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      handleSendMessage();
    }
  };

  const open = Boolean(anchorEl);
  const id = open ? 'assistant-popover' : undefined;

  return (
    <>
      <Fab
        color="primary"
        aria-label="assistant"
        onClick={handleClick}
        sx={{
          position: 'fixed',
          bottom: 20,
          left: 20,
          zIndex: 1000
        }}
      >
        <QuestionAnswerIcon />
      </Fab>

      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        transformOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
      >
        <Paper sx={{ width: 350, maxHeight: 500, display: 'flex', flexDirection: 'column' }}>
          <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Typography variant="h6">AI助手</Typography>
            <IconButton size="small" onClick={handleClose}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </Box>
          
          <Box sx={{ p: 2, height: 300, overflowY: 'auto', flexGrow: 1 }}>
            {messages.length === 0 ? (
              <Typography color="text.secondary" align="center" sx={{ mt: 10 }}>
                有什么可以帮助您的？
              </Typography>
            ) : (
              messages.map((message, index) => (
                <Box
                  key={index}
                  sx={{
                    display: 'flex',
                    justifyContent: message.isUser ? 'flex-end' : 'flex-start',
                    mb: 2
                  }}
                >
                  <Paper
                    elevation={1}
                    sx={{
                      p: 1.5,
                      maxWidth: '80%',
                      backgroundColor: message.isUser ? 'primary.light' : 'grey.100',
                      color: message.isUser ? 'white' : 'text.primary',
                      borderRadius: 2
                    }}
                  >
                    <Typography variant="body2">{message.content}</Typography>
                  </Paper>
                </Box>
              ))
            )}
            {isLoading && (
              <Box sx={{ display: 'flex', justifyContent: 'center', my: 2 }}>
                <CircularProgress size={24} />
              </Box>
            )}
            <div ref={messagesEndRef} />
          </Box>
          
          <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider', display: 'flex' }}>
            <TextField
              fullWidth
              size="small"
              placeholder="输入您的问题..."
              variant="outlined"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyPress={handleKeyPress}
              disabled={isLoading}
              sx={{ mr: 1 }}
            />
            <IconButton 
              color="primary" 
              onClick={handleSendMessage} 
              disabled={isLoading || !input.trim()}
            >
              <SendIcon />
            </IconButton>
          </Box>
        </Paper>
      </Popover>
    </>
  );
};

export default Assistant;